const until = require('../until/until')
const fs = require('fs')
const path = require('path')

const managerRoleInfoUrl = 'asset/data/managerRoleInfo.json'

const managerRoleInfoPath = path.join(__dirname, '../', managerRoleInfoUrl)

const mmsDao = {
  list: (req, res, next) => {
    console.log(req.query)

    const params = req.query

    if (params.pageNum === undefined || params.pageSize === undefined) {
      res.json(until.formatter(500, '操作失败，请确认查询信息再重试'))
      return
    }

    if (params.keyWord === '') {
      const startIndex = params.pageNum * params.pageSize
      const endIndex = (params.pageNum + 1) * params.pageSize

      const data = fs.readFileSync(managerRoleInfoPath)
      const managerRoleInfoData = JSON.parse(data.toString())

      const info = managerRoleInfoData.slice(startIndex, endIndex)
      res.json(
        until.formatter(200, '操作成功', {
          list: info,
          pageNum: params.pageNum,
          pageSize: params.pageSize,
        })
      )
      return
    }

    res.send('list')
  },
  modify: (req, res, next) => {
    console.log(req.body)

    const params = req.body

    if (params.id === undefined) {
      res.json(until.formatter(500, '操作失败，请确认修改信息再重试'))
      return
    }

    const data = fs.readFileSync(managerRoleInfoPath)
    const managerRoleInfoData = JSON.parse(data.toString())

    const index = managerRoleInfoData.findIndex((item) => item.id === params.id)

    managerRoleInfoData[index] = params

    const managerRoleInfoDataStr = JSON.stringify(managerRoleInfoData)

    fs.writeFile(managerRoleInfoPath, managerRoleInfoDataStr, (err) => {
      if (err) {
        console.error(err)
      }
      console.log('修改成功')
    })

    res.json(until.formatter(200, '修改成功'))
  },
}

module.exports = mmsDao
